from django.shortcuts import render,HttpResponseRedirect
from app.forms import wiki_form
from django.urls import reverse
from app import models
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from utils import cos, encrypt


def wiki(request, id):
    if request.method == 'GET':
        wiki_id = request.GET.get('wiki_id','')
        if wiki_id and wiki_id.isdecimal():
            wiki_obj = models.Wiki.objects.filter(id=wiki_id,project_id=id).first()
            return render(request, 'app/wiki.html',{'wiki_obj':wiki_obj})
        else:
            return render(request,'app/wiki.html')

def add(request,id):
    if request.method == 'GET':
        form = wiki_form.WikiModelForm(request)
        return render(request,'app/add_wiki.html',{'form':form})
    else:
        form = wiki_form.WikiModelForm(request,data=request.POST)
        if form.is_valid():
            if form.instance.parent:
                form.instance.depth = form.instance.parent.depth + 1
            form.instance.project_id = id
            form.save()
            url = reverse('app:wiki',kwargs={'id':id})
            return HttpResponseRedirect(url)
        return render(request,'app/add_wiki.html',{'form':form})

def wiki_catelog(request,id):
    """
    ajax请求生成wiki目录
    :param request:
    :param id:
    :return:
    """
    if request.method == 'GET':
        result = dict()
        catelogs = models.Wiki.objects.filter(project_id=id).values('id','title','parent_id').order_by('depth','id')
        result['status'] = True
        result['data'] = list(catelogs)   #querryset类型转列表
        return JsonResponse(result,safe=False)

def wiki_delete(request,id,wiki_id):
    if request.method == 'GET':
        models.Wiki.objects.filter(id=wiki_id,project_id=id).delete()
        url = reverse('app:wiki', kwargs={'id': id})
        return HttpResponseRedirect(url)

def wiki_edit(request,id,wiki_id):
    """
    编辑Wiki
    :param request:
    :param id:
    :param wiki_id:
    :return:
    """
    wiki_obj = models.Wiki.objects.filter(id=wiki_id,project_id=id).first()
    if not wiki_obj:
        url = reverse('app:wiki', kwargs={'id': id})
        return HttpResponseRedirect(url)
    if request.method == 'GET':
        form = wiki_form.WikiModelForm(request,instance=wiki_obj)
        return render(request,'app/add_wiki.html',{'form':form})
    else:
        form = wiki_form.WikiModelForm(request,data=request.POST,instance=wiki_obj)
        if form.is_valid():
            if form.instance.parent:
                form.instance.depth = form.instance.parent.depth + 1
            form.instance.project_id = id
            form.save()
            url = reverse('app:wiki', kwargs={'id': id})
            url = f'{url}?wiki_id={wiki_id}'
            return HttpResponseRedirect(url)
        return render(request, 'app/add_wiki.html', {'form': form})


@csrf_exempt
def wiki_upload(request,id):
    if request.method == 'POST':
        res = {
            'success':0,
            'message':None,
            'url':None
        }
        image_obj = request.FILES.get('editormd-image-file',None)
        if not image_obj:
            res['message'] = '文件不存在'
            return JsonResponse(res,safe=False)
        ext = image_obj.name.rsplit('.')[-1]
        key = f"{encrypt.uid(request.tracer.user.phone)}.{ext}"
        img_url = cos.upload_file(request.tracer.project.bucket, image_obj, key)
        res['success'] = 1
        res['url'] = img_url
        return JsonResponse(res,safe=False)